{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !wget https://storage.googleapis.com/bert_models/2018_11_23/multi_cased_L-12_H-768_A-12.zip\n",
    "# !unzip multi_cased_L-12_H-768_A-12.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:87: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import bert\n",
    "from bert import run_classifier\n",
    "from bert import optimization\n",
    "from bert import tokenization\n",
    "from bert import modeling\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import pandas as pd\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "with open('dataset.json') as fopen:\n",
    "    data = json.load(fopen)\n",
    "    \n",
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/tokenization.py:125: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "BERT_VOCAB = 'multi_cased_L-12_H-768_A-12/vocab.txt'\n",
    "BERT_INIT_CHKPNT = 'multi_cased_L-12_H-768_A-12/bert_model.ckpt'\n",
    "BERT_CONFIG = 'multi_cased_L-12_H-768_A-12/bert_config.json'\n",
    "\n",
    "tokenizer = tokenization.FullTokenizer(\n",
    "      vocab_file=BERT_VOCAB, do_lower_case=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from unidecode import unidecode\n",
    "\n",
    "def get_inputs(x, y):\n",
    "    input_ids, input_masks, segment_ids, ys = [], [], [], []\n",
    "    for i in tqdm(range(len(x))):\n",
    "        tokens_a = tokenizer.tokenize(unidecode(x[i]))\n",
    "        tokens_b = tokenizer.tokenize(unidecode(y[i]))\n",
    "        tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n",
    "        \n",
    "        segment_id = [0] * len(tokens)\n",
    "        input_id = tokenizer.convert_tokens_to_ids(tokens)\n",
    "        input_mask = [1] * len(input_id)\n",
    "\n",
    "        input_ids.append(input_id)\n",
    "        input_masks.append(input_mask)\n",
    "        segment_ids.append(segment_id)\n",
    "        \n",
    "        r = tokenizer.convert_tokens_to_ids(tokens_b) + [EOS]\n",
    "        if len([k for k in r if k == 0]):\n",
    "            print(y[i], i)\n",
    "            break\n",
    "        \n",
    "        ys.append(r)\n",
    "        \n",
    "    return input_ids, input_masks, segment_ids, ys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 200000/200000 [02:46<00:00, 1202.17it/s]\n"
     ]
    }
   ],
   "source": [
    "train_input_ids, train_input_masks, train_segment_ids, train_Y = get_inputs(train_X, train_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 5000/5000 [00:04<00:00, 1249.30it/s]\n"
     ]
    }
   ],
   "source": [
    "test_input_ids, test_input_masks, test_segment_ids, test_Y = get_inputs(test_X, test_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "bert_config = modeling.BertConfig.from_json_file(BERT_CONFIG)\n",
    "epoch = 20\n",
    "batch_size = 16\n",
    "warmup_proportion = 0.1\n",
    "num_train_steps = len(train_input_ids)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "119547"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bert_config.vocab_size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "BASE_PARAMS = defaultdict(\n",
    "    lambda: None,  # Set default value to None.\n",
    "\n",
    "    # Input params\n",
    "    default_batch_size=2048,  # Maximum number of tokens per batch of examples.\n",
    "    default_batch_size_tpu=32768,\n",
    "    max_length=256,  # Maximum number of tokens per example.\n",
    "\n",
    "    # Model params\n",
    "    initializer_gain=1.0,  # Used in trainable variable initialization.\n",
    "    vocab_size=32000,  # Number of tokens defined in the vocabulary file.\n",
    "    hidden_size=768,  # Model dimension in the hidden layers.\n",
    "    num_hidden_layers=6,  # Number of layers in the encoder and decoder stacks.\n",
    "    num_heads=8,  # Number of heads to use in multi-headed attention.\n",
    "    filter_size=2048,  # Inner layer dimension in the feedforward network.\n",
    "\n",
    "    # Dropout values (only used when training)\n",
    "    layer_postprocess_dropout=0.1,\n",
    "    attention_dropout=0.1,\n",
    "    relu_dropout=0.1,\n",
    "\n",
    "    # Training params\n",
    "    label_smoothing=0.1,\n",
    "    learning_rate=1.0,\n",
    "    learning_rate_decay_rate=1.0,\n",
    "    learning_rate_warmup_steps=16000,\n",
    "\n",
    "    # Optimizer params\n",
    "    optimizer_adam_beta1=0.9,\n",
    "    optimizer_adam_beta2=0.997,\n",
    "    optimizer_adam_epsilon=1e-09,\n",
    "\n",
    "    # Default prediction params\n",
    "    extra_decode_length=50,\n",
    "    beam_size=4,\n",
    "    alpha=0.6,  # used to calculate length normalization in beam search\n",
    "\n",
    "    # TPU specific parameters\n",
    "    use_tpu=False,\n",
    "    static_batch=False,\n",
    "    allow_ffn_pad=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/translation/transformer/attention_layer.py:24: The name tf.layers.Layer is deprecated. Please use tf.compat.v1.layers.Layer instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from transformer import model_utils\n",
    "from transformer import utils\n",
    "from transformer.transformer import DecoderStack\n",
    "from transformer import beam_search\n",
    "\n",
    "class Model:\n",
    "    def __init__(\n",
    "        self,\n",
    "        learning_rate = 2e-5,\n",
    "        training = True,\n",
    "    ):\n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "        self.input_masks = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        model = modeling.BertModel(\n",
    "            config=bert_config,\n",
    "            is_training=training,\n",
    "            input_ids=self.X,\n",
    "            input_mask=self.input_masks,\n",
    "            token_type_ids=self.segment_ids,\n",
    "            use_one_hot_embeddings=False)\n",
    "        \n",
    "        self.decoder_stack = DecoderStack(BASE_PARAMS, training)\n",
    "        attention_bias = model_utils.get_padding_bias(self.X)\n",
    "        \n",
    "        output_layer = model.get_sequence_output()\n",
    "        pooled_output = model.get_pooled_output()\n",
    "        embedding = model.get_embedding_table()\n",
    "        \n",
    "        with tf.name_scope(\"decode\"):\n",
    "            mask = tf.to_float(tf.not_equal(self.Y, 0))\n",
    "            decoder_inputs = tf.gather(embedding, self.Y)\n",
    "            decoder_inputs *= tf.expand_dims(mask, -1)\n",
    "            with tf.name_scope(\"shift_targets\"):\n",
    "                decoder_inputs = tf.pad(\n",
    "                    decoder_inputs, [[0, 0], [1, 0], [0, 0]])[:, :-1, :]\n",
    "            with tf.name_scope(\"add_pos_encoding\"):\n",
    "                length = tf.shape(decoder_inputs)[1]\n",
    "                decoder_inputs += model_utils.get_position_encoding(\n",
    "                    length, BASE_PARAMS[\"hidden_size\"])\n",
    "            if training:\n",
    "                decoder_inputs = tf.nn.dropout(\n",
    "                    decoder_inputs, 1 - BASE_PARAMS[\"layer_postprocess_dropout\"])\n",
    "            decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(length)\n",
    "            outputs = self.decoder_stack(\n",
    "              decoder_inputs, output_layer, decoder_self_attention_bias,\n",
    "              attention_bias)\n",
    "            \n",
    "        with tf.variable_scope('cls/predictions'):\n",
    "            with tf.variable_scope('transform'):\n",
    "                input_tensor = tf.layers.dense(\n",
    "                outputs,\n",
    "                units = bert_config.hidden_size,\n",
    "                activation = modeling.get_activation(bert_config.hidden_act),\n",
    "                kernel_initializer = modeling.create_initializer(\n",
    "                    bert_config.initializer_range\n",
    "                ),\n",
    "            )\n",
    "            input_tensor = modeling.layer_norm(input_tensor)\n",
    "\n",
    "            output_bias = tf.get_variable(\n",
    "            'output_bias',\n",
    "            shape = [bert_config.vocab_size],\n",
    "            initializer = tf.zeros_initializer(),\n",
    "            )\n",
    "            self.training_logits = tf.matmul(input_tensor, embedding, transpose_b = True)\n",
    "        print(self.training_logits)\n",
    "                \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        \n",
    "        self.optimizer = optimization.create_optimizer(self.cost, learning_rate, \n",
    "                                                       num_train_steps, num_warmup_steps, False)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        def _get_symbols_to_logits_fn(max_decode_length):\n",
    "            timing_signal = model_utils.get_position_encoding(\n",
    "                max_decode_length + 1, BASE_PARAMS[\"hidden_size\"])\n",
    "            decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(\n",
    "                max_decode_length)\n",
    "            def symbols_to_logits_fn(ids, i, cache):\n",
    "                decoder_input = ids[:, -1:]\n",
    "                mask = tf.to_float(tf.not_equal(decoder_input, 0))\n",
    "                decoder_input = tf.gather(embedding, decoder_input)\n",
    "                decoder_input *= tf.expand_dims(mask, -1)\n",
    "                decoder_input += timing_signal[i:i + 1]\n",
    "                self_attention_bias = decoder_self_attention_bias[:, :, i:i + 1, :i + 1]\n",
    "                decoder_outputs = self.decoder_stack(\n",
    "                  decoder_input, cache.get(\"encoder_outputs\"), self_attention_bias,\n",
    "                  cache.get(\"encoder_decoder_attention_bias\"), cache)\n",
    "                \n",
    "                with tf.variable_scope('cls/predictions', reuse = True):\n",
    "                    with tf.variable_scope('transform'):\n",
    "                        input_tensor = tf.layers.dense(\n",
    "                        decoder_outputs,\n",
    "                        units = bert_config.hidden_size,\n",
    "                        activation = modeling.get_activation(bert_config.hidden_act),\n",
    "                        kernel_initializer = modeling.create_initializer(\n",
    "                            bert_config.initializer_range\n",
    "                        ),\n",
    "                    )\n",
    "                    input_tensor = modeling.layer_norm(input_tensor)\n",
    "\n",
    "                    output_bias = tf.get_variable(\n",
    "                    'output_bias',\n",
    "                    shape = [bert_config.vocab_size],\n",
    "                    initializer = tf.zeros_initializer(),\n",
    "                    )\n",
    "                    logits = tf.matmul(input_tensor, embedding, transpose_b = True)\n",
    "                logits = tf.squeeze(logits, axis=[1])\n",
    "                return logits, cache\n",
    "            return symbols_to_logits_fn\n",
    "        \n",
    "        batch_size = tf.shape(output_layer)[0]\n",
    "        input_length = tf.shape(output_layer)[1]\n",
    "        max_decode_length = input_length + BASE_PARAMS[\"extra_decode_length\"]\n",
    "        symbols_to_logits_fn = _get_symbols_to_logits_fn(max_decode_length)\n",
    "        initial_ids = tf.zeros([batch_size], dtype=tf.int32)\n",
    "        cache = {\n",
    "        \"layer_%d\" % layer: {\n",
    "            \"k\": tf.zeros([batch_size, 0, BASE_PARAMS[\"hidden_size\"]]),\n",
    "            \"v\": tf.zeros([batch_size, 0, BASE_PARAMS[\"hidden_size\"]]),\n",
    "        } for layer in range(BASE_PARAMS[\"num_hidden_layers\"])}\n",
    "        cache[\"encoder_outputs\"] = output_layer\n",
    "        cache[\"encoder_decoder_attention_bias\"] = attention_bias\n",
    "        \n",
    "        decoded_ids, scores = beam_search.sequence_beam_search(\n",
    "            symbols_to_logits_fn=symbols_to_logits_fn,\n",
    "            initial_ids=initial_ids,\n",
    "            initial_cache=cache,\n",
    "            vocab_size=bert_config.vocab_size,\n",
    "            beam_size=1,\n",
    "            alpha=BASE_PARAMS[\"alpha\"],\n",
    "            max_decode_length=max_decode_length,\n",
    "            eos_id=EOS)\n",
    "        \n",
    "        top_decoded_ids = decoded_ids[:, 0, 1:]\n",
    "        self.fast_result = top_decoded_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:171: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:409: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:490: The name tf.assert_less_equal is deprecated. Please use tf.compat.v1.assert_less_equal instead.\n",
      "\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:358: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:671: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/attention_layer.py:39: The name tf.layers.Dense is deprecated. Please use tf.compat.v1.layers.Dense instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/model_utils.py:89: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/model_utils.py:71: The name tf.matrix_band_part is deprecated. Please use tf.linalg.band_part instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/autograph/converters/directives.py:119: The name tf.rsqrt is deprecated. Please use tf.math.rsqrt instead.\n",
      "\n",
      "Tensor(\"cls/predictions/MatMul:0\", shape=(?, ?, 119547), dtype=float32)\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:27: The name tf.train.get_or_create_global_step is deprecated. Please use tf.compat.v1.train.get_or_create_global_step instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:32: The name tf.train.polynomial_decay is deprecated. Please use tf.compat.v1.train.polynomial_decay instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:70: The name tf.trainable_variables is deprecated. Please use tf.compat.v1.trainable_variables instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/math_grad.py:1375: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From /home/husein/translation/transformer/beam_search.py:420: calling reduce_logsumexp_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "keep_dims is deprecated, use keepdims instead\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Model()\n",
    "\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "\n",
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if 'bert/' + name in name_to_variable:\n",
    "            assignment_map[name] = name_to_variable['bert/' + name]\n",
    "            initialized_variable_names[name] = 1\n",
    "            initialized_variable_names[name + ':0'] = 1\n",
    "        elif name in name_to_variable:\n",
    "            assignment_map[name] = name_to_variable[name]\n",
    "            initialized_variable_names[name] = 1\n",
    "            initialized_variable_names[name + ':0'] = 1\n",
    "        \n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "\n",
    "checkpoint = BERT_INIT_CHKPNT\n",
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from multi_cased_L-12_H-768_A-12/bert_model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "i = 0\n",
    "index = min(i + batch_size, len(train_input_ids))\n",
    "batch_x = train_input_ids[i: index]\n",
    "batch_x = pad_sequences(batch_x, padding='post')\n",
    "batch_mask = train_input_masks[i: index]\n",
    "batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "batch_segment = train_segment_ids[i: index]\n",
    "batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "batch_y = pad_sequences(train_Y[i: index], padding='post')\n",
    "acc, cost, r = sess.run(\n",
    "    [model.accuracy, model.cost, model.fast_result],\n",
    "    feed_dict = {\n",
    "        model.Y: batch_y,\n",
    "        model.X: batch_x,\n",
    "        model.input_masks: batch_mask,\n",
    "        model.segment_ids: batch_segment\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:13:53<00:00,  2.82it/s, accuracy=0.244, cost=4.65]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:43<00:00,  7.23it/s, accuracy=0.224, cost=4.46]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, training loss: 5.955455, training acc: 0.115196, valid loss: 4.607508, valid acc: 0.224355\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:14:48<00:00,  2.78it/s, accuracy=0.441, cost=3.09]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.43it/s, accuracy=0.473, cost=2.7] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 1, training loss: 3.678014, training acc: 0.338607, valid loss: 2.948976, valid acc: 0.445340\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:14:23<00:00,  2.80it/s, accuracy=0.496, cost=2.58]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.41it/s, accuracy=0.612, cost=2]   \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 2, training loss: 2.596153, training acc: 0.500409, valid loss: 2.366188, valid acc: 0.537981\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:13:49<00:00,  2.82it/s, accuracy=0.568, cost=2.35]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.45it/s, accuracy=0.629, cost=1.88]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 3, training loss: 2.145985, training acc: 0.573051, valid loss: 2.088281, valid acc: 0.584024\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:37<00:00,  2.87it/s, accuracy=0.606, cost=2.08]\n",
      "test minibatch loop: 100%|██████████| 313/313 [00:41<00:00,  7.49it/s, accuracy=0.633, cost=1.78]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 4, training loss: 1.887629, training acc: 0.615203, valid loss: 1.920140, valid acc: 0.612936\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:13:40<00:00,  2.83it/s, accuracy=0.61, cost=1.96]  \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:41<00:00,  7.46it/s, accuracy=0.665, cost=1.7] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 5, training loss: 1.714341, training acc: 0.643448, valid loss: 1.810929, valid acc: 0.629830\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:14:03<00:00,  2.81it/s, accuracy=0.625, cost=1.83] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.34it/s, accuracy=0.678, cost=1.58]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 6, training loss: 1.586125, training acc: 0.664397, valid loss: 1.736822, valid acc: 0.643322\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:17<00:00,  2.88it/s, accuracy=0.659, cost=1.79] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.36it/s, accuracy=0.661, cost=1.56]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 7, training loss: 1.487143, training acc: 0.680766, valid loss: 1.691175, valid acc: 0.650486\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:13:15<00:00,  2.84it/s, accuracy=0.674, cost=1.66] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.39it/s, accuracy=0.722, cost=1.42]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 8, training loss: 1.407225, training acc: 0.694288, valid loss: 1.650069, valid acc: 0.657409\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:26<00:00,  2.88it/s, accuracy=0.669, cost=1.65] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.40it/s, accuracy=0.69, cost=1.46]  \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 9, training loss: 1.340516, training acc: 0.705622, valid loss: 1.618462, valid acc: 0.663086\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:18<00:00,  2.88it/s, accuracy=0.689, cost=1.54] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.44it/s, accuracy=0.682, cost=1.46]\n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 10, training loss: 1.285427, training acc: 0.714992, valid loss: 1.601057, valid acc: 0.666801\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:12<00:00,  2.89it/s, accuracy=0.672, cost=1.51] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.45it/s, accuracy=0.694, cost=1.46] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 11, training loss: 1.240569, training acc: 0.722723, valid loss: 1.584278, valid acc: 0.669326\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:10<00:00,  2.89it/s, accuracy=0.686, cost=1.45] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:41<00:00,  7.48it/s, accuracy=0.686, cost=1.41] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 12, training loss: 1.203088, training acc: 0.729307, valid loss: 1.570970, valid acc: 0.672899\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:07<00:00,  2.89it/s, accuracy=0.703, cost=1.41] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:41<00:00,  7.49it/s, accuracy=0.698, cost=1.49] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 13, training loss: 1.172693, training acc: 0.734576, valid loss: 1.566814, valid acc: 0.674089\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:07<00:00,  2.89it/s, accuracy=0.695, cost=1.37] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:41<00:00,  7.48it/s, accuracy=0.686, cost=1.46] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 14, training loss: 1.148578, training acc: 0.738979, valid loss: 1.561730, valid acc: 0.674342\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:05<00:00,  2.89it/s, accuracy=0.703, cost=1.4]  \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:41<00:00,  7.50it/s, accuracy=0.714, cost=1.38] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 15, training loss: 1.132344, training acc: 0.741830, valid loss: 1.553435, valid acc: 0.675279\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:05<00:00,  2.89it/s, accuracy=0.706, cost=1.37] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.36it/s, accuracy=0.718, cost=1.44] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 16, training loss: 1.124852, training acc: 0.743204, valid loss: 1.556329, valid acc: 0.675844\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:17<00:00,  2.88it/s, accuracy=0.716, cost=1.37] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.36it/s, accuracy=0.71, cost=1.41] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 17, training loss: 1.124734, training acc: 0.743248, valid loss: 1.556785, valid acc: 0.676413\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:12:29<00:00,  2.87it/s, accuracy=0.701, cost=1.34] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.37it/s, accuracy=0.722, cost=1.38] \n",
      "train minibatch loop:   0%|          | 0/12500 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 18, training loss: 1.124900, training acc: 0.743367, valid loss: 1.559540, valid acc: 0.675472\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "train minibatch loop: 100%|██████████| 12500/12500 [1:14:13<00:00,  2.81it/s, accuracy=0.695, cost=1.38] \n",
      "test minibatch loop: 100%|██████████| 313/313 [00:42<00:00,  7.40it/s, accuracy=0.706, cost=1.44] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 19, training loss: 1.124544, training acc: 0.743489, valid loss: 1.559637, valid acc: 0.675199\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "import time\n",
    "\n",
    "for EPOCH in range(epoch):\n",
    "\n",
    "    train_acc, train_loss, test_acc, test_loss = [], [], [], []\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_input_ids), batch_size), desc = 'train minibatch loop'\n",
    "    )\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_input_ids))\n",
    "        batch_x = train_input_ids[i: index]\n",
    "        batch_x = pad_sequences(batch_x, padding='post')\n",
    "        batch_mask = train_input_masks[i: index]\n",
    "        batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "        batch_segment = train_segment_ids[i: index]\n",
    "        batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i: index], padding='post')\n",
    "        acc, cost, _ = sess.run(\n",
    "            [model.accuracy, model.cost, model.optimizer],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.input_masks: batch_mask,\n",
    "                model.segment_ids: batch_segment\n",
    "            },\n",
    "        )\n",
    "        train_loss.append(cost)\n",
    "        train_acc.append(acc)\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "        \n",
    "    pbar = tqdm(range(0, len(test_input_ids), batch_size), desc = 'test minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_input_ids))\n",
    "        batch_x = test_input_ids[i: index]\n",
    "        batch_x = pad_sequences(batch_x, padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i: index], padding='post')\n",
    "        batch_mask = test_input_masks[i: index]\n",
    "        batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "        batch_segment = test_segment_ids[i: index]\n",
    "        batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "        acc, cost = sess.run(\n",
    "            [model.accuracy, model.cost],\n",
    "            feed_dict = {\n",
    "                model.Y: batch_y,\n",
    "                model.X: batch_x,\n",
    "                model.input_masks: batch_mask,\n",
    "                model.segment_ids: batch_segment\n",
    "            },\n",
    "        )\n",
    "        test_loss.append(cost)\n",
    "        test_acc.append(acc)\n",
    "        pbar.set_postfix(cost = cost, accuracy = acc)\n",
    "        \n",
    "    train_loss = np.mean(train_loss)\n",
    "    train_acc = np.mean(train_acc)\n",
    "    test_loss = np.mean(test_loss)\n",
    "    test_acc = np.mean(test_acc)\n",
    "    print(\n",
    "        'epoch: %d, training loss: %f, training acc: %f, valid loss: %f, valid acc: %f\\n'\n",
    "        % (EPOCH, train_loss, train_acc, test_loss, test_acc)\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 313/313 [16:56<00:00,  3.25s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = test_input_ids[i: index]\n",
    "    batch_x = pad_sequences(batch_x, padding='post')\n",
    "    batch_y = pad_sequences(test_Y[i: index], padding='post')\n",
    "    batch_mask = test_input_masks[i: index]\n",
    "    batch_mask = pad_sequences(batch_mask, padding='post')\n",
    "    batch_segment = test_segment_ids[i: index]\n",
    "    batch_segment = pad_sequences(batch_segment, padding='post')\n",
    "    feed = {\n",
    "        model.X: batch_x,\n",
    "        model.input_masks: batch_mask,\n",
    "        model.segment_ids: batch_segment\n",
    "    }\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 1 and i not in [101, 102]])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 1 and i not in [101, 102]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.3941662"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
